package com.buobao.spring.jdbc.dao;

import com.buobao.spring.jdbc.entity.Employee;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Repository
public class EmployeeDao {
    @Resource
    private JdbcTemplate jdbcTemplate;

    public Employee findById(Long eno) {
        String sql = "select * from t_emp where empno = ?";
        Employee employee = jdbcTemplate.queryForObject(sql, new Object[]{eno}, new BeanPropertyRowMapper<>(Employee.class));
        return employee;
    }

    public List<Employee> findByDeptno(long deptno) {
        String sql = "select * from t_emp where deptno = ?";
        List<Employee> employees = jdbcTemplate.query(sql, new Object[]{deptno}, new BeanPropertyRowMapper<>(Employee.class));
        return employees;
    }

    public List<Map<String, Object>> findMapByDname(String dname) {
        String sql = "select * from t_emp t left join t_dept d on t.deptno = d.deptno where d.dname = ?";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, new Object[]{dname});
        return maps;
    }

    public void insert(Employee employee) {
        String sql = "insert into t_emp(empno,ename,job,mgr,hiredate,sal,comm,deptno)values(?,?,?,?,?,?,?,?)";
        jdbcTemplate.update(sql,new Object[]{
                employee.getEmpno(),
                employee.getEname(),
                employee.getJob(),
                employee.getMgr(),
                employee.getHiredate(),
                employee.getSal(),
                employee.getComm(),
                employee.getDeptno()
        });
    }

    public int update(Employee employee) {
        String sql = "update t_emp set ename = ?,job = ?,mgr = ?,hiredate = ?,sal = ?,comm = ?,deptno = ? where empno = ?";
        int count = jdbcTemplate.update(sql,new Object[]{
                employee.getEname(),
                employee.getJob(),
                employee.getMgr(),
                employee.getHiredate(),
                employee.getSal(),
                employee.getComm(),
                employee.getDeptno(),
                employee.getEmpno()
        });
        return count;
    }
}
